const App = {
    mixins: [Save],//配置文件，路径/utils/mixins.js
    data() {
        return {
            photo,
            category: [],
            category1: [],
            news_tags: [],
            childDataForm: [],
            childDataForm1: [],
            party_organization: [],
            dataForm: {
                Row_Status: '2',
                Environment_MicroScreen:'1',
                Environment_BigScreen:'1',
            },
            addType: '',
            disabled:false,
            value:[],
            NewsTerminal:[],
            categoryNew:[],
        };
    },
    mounted() {
        let ls_URL = window.location.href;
        let Party_Organization_Activity_SerialNumber = getQueryObject(ls_URL, "Party_Organization_Activity_SerialNumber");// 获取 nodeKey 参数
        if (Party_Organization_Activity_SerialNumber) {
            this.dataForm.Party_Organization_Activity_SerialNumber = Party_Organization_Activity_SerialNumber;
            this.skipChange();
        }
        let News_Category_SerialNumber = getQueryObject(ls_URL, "News_Category_SerialNumber");// 获取 nodeKey 参数
        if (News_Category_SerialNumber) {
            this.dataForm.News_Category_SerialNumber = News_Category_SerialNumber;
            this.skipChange();
            this.disabled = true;
        }
        let Policy_SerialNumber = getQueryObject(ls_URL, "Policy_SerialNumber");// 获取 nodeKey 参数
        if (Policy_SerialNumber) {
            this.dataForm.Party_Organization_Activity_SerialNumber = Policy_SerialNumber;
            if (!News_Category_SerialNumber) {
                this.dataForm.News_Category_SerialNumber = "NC0000000000071";
            }
            this.skipChange();
            this.disabled = true;
        }
        this.getCategory();
        this.GetNewsTerminal();
    },
    watch:{
        'dataForm.News_SerialNumber'(val){
            this.dataForm.NewsTerminal = this.dataForm.NewsTerminal ? this.dataForm.NewsTerminal.split(','):[]
            this.handleChange(this.dataForm.NewsTerminal, false)
            // if (this.dataForm.Environment_MicroScreen == '0') {
            //     this.value.push('1')
            // }
            // if (this.dataForm.Environment_MicroScreen2 == '0') {
            //     this.value.push('2')
            // }
            // if (this.dataForm.Environment_MicroScreen3 == '0') {
            //     this.value.push('3')
            // }
        }
    },
    methods: {
        GetNewsTerminal() {
            $.ajax({
                url: `${absolutepath()}api/NewsTerminal.json`,
                method: "get",
                success: (data) => {
                    this.NewsTerminal=data; 
                },
            })
        },
        skipChange(){
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'news_category',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.category = data; // 直接使用 this
                    this.addType = getQueryObject(window.location.href, "addType");// 获取 nodeKey 参数
                    if (this.addType) {
                        let obj = data.filter(i => i.News_Category == this.addType)[0];
                        if (obj) {
                            this.dataForm.News_Category_SerialNumber = obj.News_Category_SerialNumber;
                            this.dataForm.NewsTerminal = obj.NewsTerminal? obj.NewsTerminal.split(","):[]
                        }
                    } else {
                        let obj = data.filter(i => i.News_Category_SerialNumber == this.dataForm.News_Category_SerialNumber)[0];
                        if (obj) {
                            console.log(obj.NewsTerminal);
                            this.dataForm.NewsTerminal = obj.NewsTerminal? obj.NewsTerminal.split(","):[]
                        }
                    }
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
        },
        handleChange(val, is = true) {
            if (is) {
                this.dataForm.News_Category_SerialNumber = '';
            }
            let str = val.map(i => `NewsTerminal LIKE '%${i}%'`).join(" AND ");
            if (!str) return
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
                type: "POST",
                data: {
                    SQLSerialNumber: 'f_news_category',
                    Condition: '',
                    ExtensionCondition: window.btoa(unescape(encodeURIComponent(str))),
                },
                success: (data) => {
                    // this.category = data; // 直接使用 this

                    const serialNumbers = data.map(item => item.News_Category_SerialNumber);

                    // let strurl = mh + "/requestForward/requestForward?RequestURL=" +
                    //     encodeURIComponent("http://10.1.0.33:8086/api/news-categories/merged-paths?ids=" +
                    //         serialNumbers.join() + "&Router=")

                    let strurl = mh + "/requestForward/requestForward?RequestURL=" +
                        encodeURIComponent("/api/news-categories/merged-paths?ids=" +
                            serialNumbers.join())

                    console.log("Url", strurl);

                    $.ajax({
                        headers: requestHeaders(),
                        url: strurl,
                        method: "get",
                        dataType: "json",
                        success: (data1) => {
                            console.log(data1);

                            this.categoryNew = data1;
                        },
                        complete: (XMLHttpRequest) => {
                            requestPretreatment(XMLHttpRequest);
                        },
                    })

                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
        },
        getCategory() {
            // $.ajax({
            //     headers: requestHeaders(),
            //     url: `${mh}/generalBusiness/generalQueryByTableName`,
            //     type: "POST",
            //     data: {
            //         Data: 'news_category',
            //         Condition: "Row_Status='0'",
            //     },
            //     success: (data) => {
            //         this.category1 = data; // 直接使用 this
            //         this.addType = getQueryObject(window.location.href, "addType");// 获取 nodeKey 参数
            //         if (this.addType) {
            //             let obj = data.filter(i => i.News_Category == this.addType)[0];
            //             if (obj) {
            //                 this.dataForm.News_Category_SerialNumber = obj.News_Category_SerialNumber;
            //             }
            //         }
            //     },
            //     complete: (XMLHttpRequest) => {
            //         requestPretreatment(XMLHttpRequest);
            //     },
            //     dataType: "json",
            // });

            // $.ajax({
            //     headers: requestHeaders(),
            //     url: `${mh}/generalBusiness/generalQueryForObtainingTrees`,
            //     type: "GET",
            //     data: {
            //         TableName: 'news_category',
            //         NodeCode: "",
            //     },
            //     success: (data) => {
            //         this.category = data; // 直接使用 this
            //     },
            //     complete: (XMLHttpRequest) => {
            //         requestPretreatment(XMLHttpRequest);
            //     },
            //     dataType: "json",
            // });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'news_tags',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.news_tags = data; // 直接使用 this
                }, complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            // $.ajax({
            //     headers: requestHeaders(),
            //     url: `${mh}/generalBusiness/generalQueryForObtainingTrees`,
            //     type: "GET",
            //     data: {
            //         TableName: 'party_organization',
            //         NodeCode: "",
            //     },
            //     success: (data) => {
            //         this.party_organization = data; // 直接使用 this
            //     },
            //     complete: (XMLHttpRequest) => {
            //         requestPretreatment(XMLHttpRequest);
            //     },
            //     dataType: "json",
            // });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/permissionsTree/getPartyOrganizationsTreeByPermissions`,
                type: "GET",
                data: {
                  PartyOrganizationsCode: getCookie('party'), //请求参数
                },
                success: (data) => {
                  this.party_organization = data;
                },
                complete: (XMLHttpRequest) => {
                  requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
              });
        },
        changeCategory() {
            this.dataForm.Party_Organization_Activity_SerialNumber = ''
        },
        handleRemove1(formName) {
            if (this.action === 'Add') {
                if (this[formName].length > 0) {
                    this[formName].pop();
                } else {
                    this.$message({
                        message: '不能在删除了',
                        type: 'warning'
                    })
                }
            } else if (this.action === 'Modify') {
                if (this[formName].filter(item => item.Row_Status != '1').length > 0) {
                    let i = this[formName].filter(item => item.Row_Status != '1').length - 1
                    let obj = this[formName].filter(item => item.Row_Status != '1')[i]
                    if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                        this[formName].pop();
                    } else {
                        this.$confirm('该操作将删除此条数据,是否继续?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                        }).then(() => {
                            this[formName].filter(item => item.Row_Status != '1')[i].Row_Status = '1'
                        }).catch(() => {
                            this.$message({
                                type: 'warning',
                                message: '已取消删除'
                            });
                        });
                    }
                } else {
                    this.$message({
                        message: '不能在删除了',
                        type: 'warning'
                    })
                }
            }
        },
        async handleSubmit() {
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.loading = true;
                let ls_URL = window.location.href;
                const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
                let lJSONObject_Data_Options = new Object();
                lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

                let ls_MainTableName = lJSONObject_Data_Options.TableName;
                let ls_DataForm = lJSONObject_Data_Options.form;
                //没有子表下面内容就会报错，try/catch抛出异常
                try {
                    //可能涉及多个子表
                    document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
                        let lJSONObject_ChildData_Options = new Object();
                        lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

                        let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
                        let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
                        // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
                        //建立子表结构体
                        let JSONArray_ChildRecord = new Array();
                        JSONArray_ChildRecord = this[ls_ChildDataForm];
                        if (!this[ls_DataForm].Children) {
                            this[ls_DataForm].Children = new Object();
                        }
                        this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
                    })
                } catch (error) {

                }
                //建立新增提交结构
                let dataForm = deepClone(this[ls_DataForm]);
                dataForm.NewsTerminal = dataForm.NewsTerminal.length > 0 ? dataForm.NewsTerminal.join(','):''
                let lJSONObject_DataSet = new Object();
                if (action == 'Add') {
                    if (this.nodeKey) {
                        dataForm.Parent_SerialNumber = this.nodeKey;
                    }
                    dataForm.News_Publish_Datetime = getYMDHMSDate();
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(dataForm);
                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
                    lJSONObject_DataSet[action] = lJSONObject_Table;
                } else if (action == 'Modify') {
                    const { add, modify } = this.deal(dataForm);
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(modify);

                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;

                    lJSONObject_DataSet[action] = lJSONObject_Table;
                    if (add != null) {
                        let lJSONArray_Record_Add = new Array();
                        lJSONArray_Record_Add.push(add);
                        let lJSONObject_Table_Add = new Object();
                        lJSONObject_Table_Add[ls_MainTableName] = lJSONArray_Record_Add;
                        lJSONObject_DataSet['Add'] = lJSONObject_Table_Add;
                    }
                }
                let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                if (!lJSONObject_DataSet['Add']) {
                    lJSONObject_DataSet['Add'] = new Object();
                }
                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                    Operation_Type: '0',
                    Operation_Path: this.relativePath,
                    Operation_Main,
                    Operation_Interface: "generalSave",
                    Operation_IP: getIpAddress()
                }]
                submitSave(lJSONObject_DataSet,(res)=>{
                    if (res.Status == 'success') {
                        window.history.go(-1);
                    }
                    this.loading = false;
                })
                // $.ajax({
                //     headers: requestHeaders(),
                //     url: `${mh}/generalBusiness/generalSave`,
                //     method: "post",
                //     data: {
                //         Data: JSON.stringify(lJSONObject_DataSet),
                //     },
                //     success: (res) => {
                //         if (res.Status == 'success') {
                //             window.history.go(-1);
                //         }
                //     },
                //     complete: (XMLHttpRequest) => {
                //         this.loading = false;
                //         requestPretreatment(XMLHttpRequest);
                //     }
                // });
            }
        },
    },
};
const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
app.component('yl-upload', ylUpload);
app.component('yl-cascader', ylCascader)
app.component('yl-text-editor', ylTextEditor);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
